package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.mapper.UserRoleMapper;
import com.mk.model.entity.UserRole;
import com.mk.service.IUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 5:18 PM 3/13/18
 */
@Service
public class UserRoleService extends BaseService<UserRoleMapper,UserRole> implements IUserRoleService {

    @Override
    public List<UserRole> findByUserId(Long userId) {
        return super.selectList(new EntityWrapper<UserRole>().eq("user_id",userId));
    }

    @Override
    public List<UserRole> findByRoleId(Long roleId) {
        return super.selectList(new EntityWrapper<UserRole>().eq("role_id",roleId));
    }

    @Override
    public Boolean changeUserRole(Long userId, List<Long> roleId) {
        if(userId == null || CollectionUtils.isEmpty(roleId))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择需要编辑的人员及角色信息");
        super.delete(new EntityWrapper<UserRole>().eq("user_id",userId));
        if(!CollectionUtils.isEmpty(roleId)){
            List<UserRole> userRoles = new ArrayList<>();
            for(Long rId : roleId){
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(rId);
                userRoles.add(userRole);
            }
            return super.insertBatch(userRoles);
        }
        return false;
    }
}
